﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinFromMediaPlayerDemo.Controls;
using WinFromMediaPlayerDemo.Forms;
using WinFromMediaPlayerDemo.Common;
using WinFromMediaPlayerDemo.Model;
using System.Collections.Concurrent;
using WMPLib;
using Microsoft.AspNet.SignalR.Client;
using System.Threading.Tasks;
using WinFromMediaPlayerDemo.Interface;
using WinFromMediaPlayerDemo.Provider;
using System.IO;

namespace WinFromMediaPlayerDemo
{
    public partial class MainFrom : Form
    {
        /// <summary>
        /// 公共实例对象
        /// </summary>
        private IMessageProvider _MessageProvider;
        private IWMPMangerProvider _WMPMangerProvider;
        private SignalrRealService _SignalrRealService;




        public MainFrom()
        {
            InitializeComponent();
        }

        private void AxWindowsMediaPlayer1_MediaChange(object sender, AxWMPLib._WMPOCXEvents_MediaChangeEvent e)
        {
            this.lblVideoInfo.Text = $"{System.IO.Path.GetFileName(axWindowsMediaPlayer1.currentMedia.sourceURL)}";
        }

        /// <summary>
        /// SignalR接收服务器文件上传通知事件实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _SignalrRealService_ServerFileUpdatedEventHander(object sender, EventArgs e)
        {
            _WMPMangerProvider.ActionManager(WMPActionType.Stop);
            this.Invoke(new Action(() =>
            {
                CheckUpdate(() => {
                    string[] localCacheFiles = FileHandler.GetLocalCacheFileList();
                    _WMPMangerProvider.ReloadPlayList(localCacheFiles);
                    _WMPMangerProvider.ActionManager(WMPActionType.Play);
                });
            }));
        }

        private void AxWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            string strState = "";
            switch (e.newState)
            {
                case 1:strState = "停止";break;
                case 2:strState = "暂停";break;
                case 3:strState = "播放";break;
                case 6:strState = "正在缓冲";break;
                case 8:strState = "完成播放";break;
                case 9:strState = "正在连接";break;
                case 10:strState = "准备就绪";break;
            }
            this.lblPlayState.Text = strState;
            //只有播放状态允许全屏
            if(e.newState ==3)
            {
                this.btnPause.Enabled = true;
                this.btnPlay.Enabled = false;
            }
            else if (e.newState == 2)
            {
                this.btnPause.Enabled = false;
                this.btnPlay.Enabled = true;
            }
            this.btnFullScreen.Enabled = (3 == e.newState);
        }

        private void LoadPlayList()
        {
            string[] localCacheFiles = FileHandler.GetLocalCacheFileList();
            IWMPPlaylist playList = axWindowsMediaPlayer1.playlistCollection.newPlaylist("MyPlayList"); //新建列表
            IWMPMedia media;

            foreach (var item in localCacheFiles)
            {
                media = axWindowsMediaPlayer1.newMedia(item); //参数为歌曲路径
                playList.appendItem(media);
            }

            axWindowsMediaPlayer1.currentPlaylist = playList;
            
            axWindowsMediaPlayer1.Ctlcontrols.play();    //开始播放
        }

        private bool CheckUpdate(Action uploadCompletedCallback =null)
        {
            if (FileHandler.IsUpdate() && !FileDownloadForm.IsBusy)
            {
                FileDownloadForm.IsBusy = true;
                //var updateForm = new UpdateRemoteFileForm();
                var updateForm = new FileDownloadForm();
                updateForm.FormClosed += (s, arg) =>
                {
                    uploadCompletedCallback?.Invoke();
                    FileDownloadForm.IsBusy = false;
                };
                updateForm.StartPosition = FormStartPosition.CenterParent;
                updateForm.ShowDialog(this);
                return true;
            }
            return false;
        }


        private void MainFrom_Load(object sender, EventArgs e)
        {
            string[] localCacheFiles = FileHandler.GetLocalCacheFileList();
            //公共实例初始化
            _MessageProvider = new CustomeMessageProvider(this);
            _WMPMangerProvider = new WMPManager(this.axWindowsMediaPlayer1, localCacheFiles, _MessageProvider);
            //配置项目检查
            if (!SettingForm.CheckSettings())
            {
                new SettingForm(_WMPMangerProvider).ShowDialog();
                return;
            }
            



            //signalr
            _SignalrRealService = new SignalrRealService(_MessageProvider, _WMPMangerProvider, Global.Default.SignalRServerAddress);
            _SignalrRealService.ServerFileUpdatedEventHander += _SignalrRealService_ServerFileUpdatedEventHander;
            _SignalrRealService.InitSignalRConnection();


            FileHandler._MessageProvider = _MessageProvider;

            //初始化配置windows media player
            axWindowsMediaPlayer1.PlayStateChange += AxWindowsMediaPlayer1_PlayStateChange;
            axWindowsMediaPlayer1.MediaChange += AxWindowsMediaPlayer1_MediaChange;
            axWindowsMediaPlayer1.uiMode = "none";
            axWindowsMediaPlayer1.fullScreen = false;
            axWindowsMediaPlayer1.settings.setMode("loop", true);



            CheckUpdate(() =>
            {
                localCacheFiles = FileHandler.GetLocalCacheFileList();
                _WMPMangerProvider.ReloadPlayList(localCacheFiles);
                _WMPMangerProvider.ActionManager(WMPActionType.Play);
            });
        }

        private void bnFullScreen_Click(object sender, EventArgs e)
        {
            axWindowsMediaPlayer1.fullScreen = this.btnPause.Checked;
            
        }

        private void axWindowsMediaPlayer1_KeyUpEvent(object sender, AxWMPLib._WMPOCXEvents_KeyUpEvent e)
        {
            if(e.nKeyCode == 27)//esc键按下退出全屏
            {
                axWindowsMediaPlayer1.fullScreen = false;
            }
            
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            SettingForm settingForm = new SettingForm(_WMPMangerProvider);
            settingForm.ShowDialog(this);
        }


        private void btnPlay_Click(object sender, EventArgs e)
        {
            this._WMPMangerProvider.ActionManager(WMPActionType.Play);
        }

        private void btnCacheFile_Click(object sender, EventArgs e)
        {
            new LocalCacheFileForm().ShowDialog();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            this._WMPMangerProvider.ActionManager(WMPActionType.Pause);
        }
    }
}
